"use strict";

const md5 = require('md5');   //MD5
const crypto = require('crypto-js');
const WebSocket = require('ws');
const moment = require('moment-timezone');
const _ = require('lodash');
const {watch} = require('watch-object');
const BFX  = require('bitfinex-api-node');
const ccxt = require('ccxt');
const decimal = require('decimal.js')
class Bot  {
    constructor ({
            symbol,
            ok_key,
            ok_secret,
            ok_fee,
            finex_key,
            finex_secret,
            finex_fee,
            slippage,
            margin_slippage,
            min_vol,
            max_vol,
        }){
        this.symbol = symbol;
        this.ok_key = ok_key;
        this.ok_secret = ok_secret;
        this.ok_fee = ok_fee;
        this.finex_key = finex_key;
        this.finex_secret = finex_secret;
        this.finex_fee = finex_fee;
        this.slippage = slippage;
        this.margin_slippage = margin_slippage;
        this.min_vol = min_vol;
        this.max_vol = max_vol;
        //OK现货地址
        this.ok_ws_url = 'wss://real.okex.com:10441/websocket';
        //finex ws地址wss://api.bitfinex.com/ws/2
        // this.finex_ws_url = 'wss://api.bitfinex.com/ws';
        //交易开关
        this.switcher = {
            tradable : true,
            ok : false,
            finex: false
        };
        // 行情
        this.markets ={
            ok : {
                ask : [0,0],
                bid : [0,0]
            },
            finex: {
                ask : [0,0],
                bid : [0,0]
            }
        };
        //钱包
        this.wallets = {
            ok : {
                coin : [],
                usd : []
            },
            finex : {
                coin : 0,
                usd : 0
            }
        };
        this.orders = {
            status : 'waiting',
            ok : {
                id : 0,     //number
                price : 0,
                vol : 0,
                complete : 0
            },
            ok_old : {
                id : 0,     //number
                price : 0,
                vol : 0,
                complete : 0
            },
            finex : {
                id : 0,
                vol : 0
            }
        };
        this.marginOrders={
            bid : {
                id : 0,     //number
                price : 0,
                vol : 0,
                complete : 0,
                active : 'waiting'
            },
            ask : {
                id : 0,     //number
                price : 0,
                vol : 0,
                complete : 0,
                active : 'waiting'
            }
        }
        this.bitfinex_rest  = new ccxt.bitfinex ({
            // verbose: true,
            apiKey: this.finex_key,
            secret: this.finex_secret,
        });
        this.ok_rest = new ccxt.okex ({
            // verbose: true,
            apiKey: this.ok_key,
            secret: this.ok_secret,
        });

    }
    init(){
        this._ok_ws ();
        this._finex_ws ();
        setTimeout(()=>{
            this._marketWatch ();
        },5000);
        setInterval(()=>{
            this._log(`
                markets: ${JSON.stringify(this.markets)}
                wallets: ${JSON.stringify(this.wallets)}
                switcher: ${JSON.stringify(this.switcher)}
                orders: ${JSON.stringify(this.orders)}
            `)
        },60000)
    }
     _marketWatch (){
        watch(this.markets.ok, ['ask','bid'], (newVal, oldVal)=> {
            const step = this._arbitrage();
            if(this._preCheck() || step === 'order-1' || step === 'order-2'){
                this._makeRequest(step)
            }

        });
        watch(this.markets.finex, ['ask','bid'], (newVal, oldVal)=> {
            const step = this._arbitrage();
            if(this._preCheck() || step === 'order-1' || step === 'order-2'){
                this._makeRequest(step)
            }
        });
        watch(this.orders.ok, 'complete', (newVal, oldVal)=> {
            this.switcher.tradable = false;
            let finex_market;
            let {ok, finex} = this.orders;
            let quantity = 0;
            if( oldVal === finex.vol){
                if( newVal - oldVal >= 0.2){
                    quantity = newVal - oldVal;
                }else{
                    this.switcher.tradable = true;
                    return;
                }
            }else if(oldVal > finex.vol){
                if( newVal - finex.vol >= 0.2){
                    quantity = newVal - finex.vol;
                }else{
                    this.switcher.tradable = true;
                    return;
                }
            }
            if(ok.vol > 0){
                this.bitfinex_rest.createMarketSellOrder ('BTG/USD', quantity);
            }else if(ok.vol < 0){
                this.bitfinex_rest.createMarketBuyOrder ('BTG/USD', quantity);
            }
            this._log(`执行finex交易`)
        });
    }
     async _makeRequest(step, {orders, switcher, _log, _createLimitOrder, _cancelOrder, _createMarketOrder} = this){
        switch (orders.status){
            case 'waiting':
                switch (step){
                    case 'waiting':
                        break;
                    case 'order-1':
                    //市价卖ok，买入finex
                    {
                        switcher.tradable= false;
                        _log(`status:${orders.status}===>${step}`)
                        await _createMarketOrder ('order-1');
                        switcher.tradable = true;
                        break;
                    }
                    case 'order-2':
                    //市价卖finex，买入ok
                    {
                        switcher.tradable= false;
                        _log(`status:${orders.status}===>${step}`)
                        await _createMarketOrder ('order-2');
                        switcher.tradable = true;
                        break;
                    }
                    case 'OK-ask-one':
                    {
                        switcher.tradable= false;
                        _log(`status:${orders.status}===>${step}`)
                        const createdOrder = await _createLimitOrder ('ask',step);
                        console.log(createdOrder)
                        if(createdOrder){
                            orders.status = step;
                            switcher.tradable = true;
                        }else{
                            _log(`${orders.status}=====>>>${step}订单信息错误`)
                        }
                        break;
                    }
                    case 'OK-bid-one':
                    {
                        switcher.tradable= false;
                        _log(`status:${orders.status}===>${step}`)
                        const createdOrder = await _createLimitOrder ('bid',step);
                        console.log(createdOrder)
                        if( createdOrder ){
                            orders.status = step;
                            switcher.tradable = true;
                        }else{
                            _log(`${orders.status}=====>>>${step}订单信息错误`)
                        }
                        break;
                    }
                }
                break;
            case 'OK-ask-one':
                switch (step){
                    case 'waiting':
                    {
                        switcher.tradable = false;
                        _log(`status:${orders.status}===>${step}`)
                        const canceledOrder = await _cancelOrder (orders.ok);
                        if(canceledOrder){
                            orders.status = step;
                            switcher.tradable = true;
                        }else{
                            _log(`${orders.status}=====>>>${step}订单信息错误`)
                        }
                        break;
                    }
                    case 'order-1':
                    //市价卖ok，买入finex
                    {
                        switcher.tradable= false;
                        _log(`status:${orders.status}===>${step}`)
                        await _createMarketOrder ('order-1');
                        switcher.tradable = true;
                        break;
                    }
                    case 'order-2':
                    //市价卖finex，买入ok
                    {
                        switcher.tradable= false;
                        _log(`status:${orders.status}===>${step}`)
                        await _createMarketOrder ('order-2');
                        switcher.tradable = true;
                        break;
                    }
                    case 'OK-ask-one':
                    {
                        switcher.tradable= false;
                        _log(`status:${orders.status}===>${step}`)
                        if(orders.ok.price === markets.ok.ask[0]){
                            // 判断是否卖一   是
                            switcher.tradable = true;
                            break;
                        }
                        // 判断是否卖一   不是
                        _log(`OK订单不是卖一单,重新下单`);
                        const createdOrder = await _createLimitOrder ('ask',step);
                        const canceledOrder = await _cancelOrder (orders.ok_old);
                        if( createdOrder && canceledOrder){
                            orders.status = step;
                            switcher.tradable = true;
                        }else{
                            _log(`${orders.status}=====>>>${step}订单信息错误`)
                        }
                        break;
                    }
                    case 'OK-bid-one':
                        switcher.tradable= false;
                        _log(`status:${orders.status}===>${step}`)
                        const createdOrder = await _createLimitOrder ('bid',step);
                        const canceledOrder = await _cancelOrder (orders.ok_old);
                        if( createdOrder && canceledOrder){
                            orders.status = step;
                            switcher.tradable = true;
                        }else{
                            _log(`${orders.status}=====>>>${step}订单信息错误`)
                        }
                        break;
                }
                break;
            case 'OK-bid-one':
                switch (step){
                    case 'waiting':
                    {
                        switcher.tradable = false;
                        _log(`status:${orders.status}===>${step}`)
                        const canceledOrder = await _cancelOrder (orders.ok);
                        if( canceledOrder){
                            orders.status = step;
                            switcher.tradable = true;
                        }else{
                            _log(`${orders.status}=====>>>${step}订单信息错误`)
                        }
                        break;
                    }
                    case 'order-1':
                        //市价卖ok，买入finex
                    {
                        switcher.tradable= false;
                        _log(`status:${orders.status}===>${step}`)
                        await _createMarketOrder ('order-1');
                        switcher.tradable = true;
                        break;
                    }
                    case 'order-2':
                        //市价卖finex，买入ok
                    {
                        switcher.tradable= false;
                        _log(`status:${orders.status}===>${step}`)
                        await _createMarketOrder ('order-2');
                        switcher.tradable = true;
                        break;
                    }
                    case 'OK-ask-one':
                    {
                        switcher.tradable= false;
                        _log(`status:${orders.status}===>${step}`)
                        const createdOrder = await _createLimitOrder ('ask',step);
                        const canceledOrder = await _cancelOrder (orders.ok_old);
                        if( createdOrder && canceledOrder){
                            orders.status = step;
                            switcher.tradable = true;
                        }else{
                            _log(`${orders.status}=====>>>${step}订单信息错误`)
                        }
                        break;
                    }
                    case 'OK-bid-one':
                    {
                        switcher.tradable= false;
                        _log(`status:${orders.status}===>${step}`)
                        if(orders.ok.price === markets.ok.bid[0]){
                            // 判断是否买一   是
                            switcher.tradable = true;
                            break;
                        }
                        // 判断是否买一   不是
                        _log(`OK订单不是买一单，重新下单`);
                        const createdOrder = await _createLimitOrder ('bid',step);
                        const canceledOrder = await _cancelOrder (orders.ok_old);
                        if( createdOrder && canceledOrder){
                            orders.status = step;
                            switcher.tradable = true;
                        }else{
                            _log(`${orders.status}=====>>>${step}订单信息错误`)
                        }
                        break;
                    }
                }
                break;
            default:
                _log(`未处理的orders.status:${orders.status}`);
                break;
        }
    }
    _ok_ws (){
        //套利的虚拟货币
        const target = this.symbol[0];
        const webSocket = new WebSocket(this.ok_ws_url);
        let timer = null;
        webSocket.on('open',()=>{
            //登陆
            webSocket.send(JSON.stringify({
                event: 'login',
                parameters:{
                    api_key: this.ok_key,
                    sign: this._ok_sign()
                }
            }))
            //订阅用户信息
            webSocket.send(JSON.stringify({
                event : 'addChannel',
                channel:'ok_spot_userinfo',
                parameters:{
                    api_key : this.ok_key,
                    sign : this._ok_sign()
                }
            }));
            //订阅交易信息
            webSocket.send(JSON.stringify({
                event : 'addChannel',
                channel:'ok_sub_spot_btg_usdt_order ',
                parameters:{
                    symbol : 'btg_usdt'
                }
            }));
            //订阅余额信息
            webSocket.send(JSON.stringify({
                event : 'addChannel',
                channel:'ok_sub_spot_btg_usdt_balance',
                parameters:{
                    symbol : 'btg_usdt'
                }
            }));
            //订阅深度
            webSocket.send(JSON.stringify({event:'addChannel',channel:'ok_sub_spot_'+target+'_usdt_depth_5'}));
            //每30S发送心跳
            setInterval(()=>{
                webSocket.send(JSON.stringify({event:'ping'}));
                //31s无回答则断开连接
                timer = setTimeout(()=>{
                    this._log('ok-ws心跳超时未响应,关闭交易开关');
                    this.switcher.ok = false;
                },31000)
            },30000);
            this._log('ok-ws连接')

        });
        webSocket.on('message',(event)=>{
            const raw_data = JSON.parse(event);
            //判断心跳 {"event":"pong"}
            if(!Array.isArray(raw_data)){
                if(raw_data.event==='pong'){
                    clearTimeout(timer);
                }
            }else{
                const data=JSON.parse(event)[0];
                switch(data.channel){
                    case 'ok_spot_userinfo':
                        const {free,freezed} = data.data.info.funds;
                        const freeCoin = Number.parseFloat(free[target]);
                        const freezedCoin = Number.parseFloat(freezed[target]);
                        const freeUsd = Number.parseFloat(free.usdt);
                        const freezedUsd = Number.parseFloat(freezed.usdt);
                        this.wallets.ok.coin = [freeCoin,freezedCoin];
                        this.wallets.ok.usd = [freeUsd, freezedUsd];
                        // 判断资产是否可以进行交易
                        if(freeCoin>1 || freeUsd>50){
                            this.switcher.ok = true;
                            this._log(`获取到OK资产信息: 
                            ${target}: free: ${freeCoin},freezed: ${freezedCoin}
                            usd: free: ${freeUsd} ,freezed: ${freezedUsd}
                            可以进行交易
                            `)
                        }else{
                            this.switcher.ok = false;
                            this._log(`获取到OK资产信息: 
                            ${target}: free: ${freeCoin},freezed: ${freezedCoin}
                            usd: free: ${freeUsd} ,freezed: ${freezedUsd}
                            资金不足，不能交易
                            `)
                        }
                        break;
                    case 'ok_sub_spot_'+target+'_usdt_depth_5':
                        const {asks, bids, timestamp} = data.data;
                        const spans = Date.now() - timestamp;
                        if(spans>100){
                            this._log(`ok延迟过高${spans}`)
                            this.switcher.ok = false;
                            break;
                        }
                        const ask_one = asks.pop();
                        const bid_one = bids[0];
                        if(
                            this.markets.ok.ask[0]!==ask_one[0] ||
                            this.markets.ok.ask[1]!==ask_one[1] ||
                            this.markets.ok.bid[0]!== bid_one[0] ||
                            this.markets.ok.bid[1]!== bid_one[1]){
                            this.markets.ok.ask = [...ask_one];
                            this.markets.ok.bid = [...bid_one];
                        }
                        this.switcher.ok = true;
                        break;
                    case 'ok_sub_spot_btg_usdt_order':
                        const {symbol, orderId, completedTradeAmount, status, tradeType} = data.data
                        if(tradeType === 'sell' || tradeType === 'buy'){
                            if( symbol === 'btg_usdt' && this.orders.ok.id === orderId){
                                switch (status) {
                                    case 1 :   //部分
                                    case 2 :   //完全
                                        console.log(`complete更新:${completedTradeAmount} ${Number.parseFloat(completedTradeAmount)}`)
                                        this.orders.ok.complete = Number.parseFloat(completedTradeAmount);
                                        console.log(data.data)
                                        this._log(`order更新`);
                                        break;
                                }
                            }
                        }

                        break;
                    case 'ok_sub_spot_btg_usdt_balance':
                    {
                        const { free, freezed } = data.data.info;
                        if(free.usdt){
                            this.wallets.ok.usd = [free.usdt, freezed.usdt]
                        }
                        else if(free.btg){
                            this.wallets.ok.coin = [free.btg, freezed.btg]
                        }
                    }
                        break;
                    default:
                        break;

                }
            }




        });
        webSocket.on('close' ,()=>{
            this._log('ok-ws连接关闭 onclose');
            this.switcher.ok = false;
            this._ok_ws();
        })
        webSocket.on('error' ,()=>{
            this._log('ok-ws连接关闭 onerror');
            this.switcher.ok = false;
            this._ok_ws();
        })

    }
    _finex_ws (){
        const bfx = new BFX({
            apiKey: this.finex_key,
            apiSecret: this.finex_secret,
            ws: {
                autoReconnect: true,
                // seqAudit: true,
                packetWDDelay: 10 * 1000
            }
        });
        const ws = bfx.ws(2, {
            manageOrderBooks: true,  // tell the ws client to maintain full sorted OBs
            transform: true          // auto-transform array OBs to OrderBook objects
        })
        ws.on('error', (err) => {
            this.switcher.finex = false;
            this._log(`finex-ws错误`)
            console.log(err)
        })
        ws.on('open', () => {
            ws.auth();
            ws.subscribeOrderBook('tBTGUSD')
        })
        ws.on('message',(msg)=>{
            // console.log(msg)
        })
        let lastMidPrice = -1;
        let midPrice;
        // 'ob' is a full OrderBook instance, with sorted arrays 'bids' & 'asks'
        ws.onOrderBook({ symbol: 'tBTGUSD' }, (ob) => {
            midPrice = ob.midPrice();
            if (midPrice !== lastMidPrice) {
                if(
                    this.markets.finex.bid[0]!==ob.bids[0][0] ||
                    this.markets.finex.bid[1]!==ob.bids[0][2] ||
                    this.markets.finex.ask[0]!==ob.asks[0][0] ||
                    this.markets.finex.ask[1]!==ob.asks[0][2])
                {
                    this.markets.finex.bid = [ob.bids[0][0],ob.bids[0][2]];
                    this.markets.finex.ask = [ob.asks[0][0],ob.asks[0][2]];
                    this.switcher.finex = true;
                }
            }else{
                this.switcher.finex = false;
            }

        });
        ws.onWalletSnapshot({}, (property)=>{
            // console.log(property)
            for (let coin of property){
                if(coin.currency === 'BTG' && coin.type === 'exchange'){
                    this.wallets.finex.coin = coin.balance;
                }
                else if(coin.currency === 'USD' && coin.type === 'exchange'){
                    this.wallets.finex.usd = Number.parseInt((new decimal(coin.balance)).toFixed(0));
                }
            }
            if(this.wallets.finex.coin>0.2 || this.wallets.finex.usd>30){
                this.switcher.finex = true;
                this._log(`获取到finex资产信息: 
                           btg: ${this.wallets.finex.coin}
                           usd: ${this.wallets.finex.usd}
                           可以进行交易
                           `)
            }else{
                this.switcher.finex = false;
                this._log(`获取到finex资产信息: 
                           btg: ${this.wallets.finex.coin}
                           usd: ${this.wallets.finex.usd}
                           资金不足，不能交易
                           `)
            }
        });
        ws.onWalletUpdate({}, (property)=>{
            // console.log(property)
            for (let coin of property){
                if(coin.currency === 'BTG' && coin.type === 'exchange'){
                    this.wallets.finex.coin = coin.balance;
                }
                else if(coin.currency === 'USD' && coin.type === 'exchange'){
                    this.wallets.finex.usd = Number.parseInt((new decimal(coin.balance)).toFixed(0));
                }
            }
            if(this.wallets.finex.coin>0.2 || this.wallets.finex.usd>30){
                this.switcher.finex = true;
                this._log(`更新finex资产信息: 
                           btg: ${this.wallets.finex.coin}
                           usd: ${this.wallets.finex.usd}
                           可以进行交易
                           `)
            }else{
                this.switcher.finex = false;
                this._log(`更新finex资产信息: 
                           btg: ${this.wallets.finex.coin}
                           usd: ${this.wallets.finex.usd}
                           资金不足，不能交易
                           `)
            }
        });
        ws.onOrderSnapshot({}, (orders) => {
            if (orders.length === 0) {
                console.log('no open orders')
                return
            }
            console.log(`${orders.length} open orders`)

            // ws.cancelOrders(orders).then(() => {
            //     console.log('cancelled orders')
            // })
        });
        ws.onOrderUpdate({}, (orders) => {
            if (orders.length === 0) {
                console.log('no open orders')
                return
            }
            console.log(`orderupdate`)
            console.log(orders)

            // ws.cancelOrders(orders).then(() => {
            //     console.log('cancelled orders')
            // })
        });
        ws.open()

    }
    _log (text){
        console.log(`${text}  ${moment().tz('Asia/Shanghai').format()}`)
    }
    _arbitrage ({ok,finex}=this.markets){
        const {ask : finex2, bid : finex1} = finex;
        const {ask : ok4, bid : ok3} = ok;
        const {ok_fee,finex_fee,slippage} = this;
        const { bid, ask} = this.marginOrders;
        const threshold = 1+ok_fee+finex_fee+slippage;
        const ratio32 = ok3[0]/finex2[0];
        const ratio42 = ok4[0]/finex2[0];
        const ratio13 = finex1[0]/ok3[0];
        const ratio14 = finex1[0]/ok4[0];
        // 4>2
        if(ratio42>1){
            // 3>2
            if(ratio32>1){

                // 3/2>1+a+b
                if(ratio32>=threshold){

                    return 'order-1';
                }
                // 3/2<1+a+b
                else{
                    if(ratio42>threshold){
                        ask.active = 'waiting';
                        bid.active = 'active';
                        return 'OK-ask-one';
                    }else{
                        ask.active = 'active';
                        bid.active = 'active';
                        return 'waiting';
                    }
                }
            }
            // 1<3<2
            else if(ratio32<1 && ratio13<1){
                if(ratio42>threshold){
                    ask.active = 'waiting';
                    bid.active = 'active';
                    return 'OK-ask-one';
                }else{
                    ask.active = 'active';
                    bid.active = 'active';
                    return 'waiting';
                }
            }
            // 3<1
            else if(ratio13>1){
                if(ratio42>threshold && ratio13>threshold){
                    return (ratio42>ratio13 ? 'OK-ask-one' : 'OK-bid-one');
                }else if(ratio42>threshold){
                    ask.active = 'waiting';
                    bid.active = 'active';
                    return 'OK-ask-one';
                }else if(ratio13>threshold){
                    ask.active = 'active';
                    bid.active = 'waiting';
                    return 'OK-bid-one';
                }else{
                    ask.active = 'active';
                    bid.active = 'active';
                    return 'waiting';
                }
            }
        }
        // 1<4<2
        else if( ratio14<1 && ratio42<1){
            // 3<1
            if(ratio13>1){
                // 1/3>1+a+b
                if(ratio13>threshold){
                    ask.active = 'active';
                    bid.active = 'waiting';
                    return 'OK-bid-one'
                }
                // 1/3<1+a+b
                else{
                    ask.active = 'active';
                    bid.active = 'active';
                    return 'waiting';
                }
            }
            // 1<3
            else{
                ask.active = 'active';
                bid.active = 'active';
                return 'waiting';
            }
        }
        // 4<1
        else if(ratio14>1){
            // 1/4<1+a+b
            if(ratio14>1.01){
                return 'order-2'
            }
            // 1/4<1+a+b
            else{
                // 1/3>1+a+b
                if(ratio13>threshold){
                    ask.active = 'active';
                    bid.active = 'waiting';
                    return 'OK-bid-one';
                }
                // 1/3<1+a+b
                else{
                    ask.active = 'active';
                    bid.active = 'active';
                    return 'waiting'
                }
            }
        }
    }
    _preCheck (){
       return (this.switcher.ok && this.switcher.finex && this.switcher.tradable )
    }
    _ok_sign (){
        return (md5("api_key=" + this.ok_key + "&secret_key=" + this.ok_secret).toUpperCase());
    }
    _generateAskOne (num){
        return (Number.parseFloat(new decimal(num).times(10000).minus(1).dividedBy(10000).toString()))
    }
    _generateBidOne (num){
        return (Number.parseFloat(new decimal(num).times(10000).plus(1).dividedBy(10000).toString()))
    }
    async _cancelOrder (order, {ok_rest}= this){
        // { result: true, order_id: '65474135' }
        const cancel =await ok_rest.cancelOrder(order.id,'BTG/USDT');
        if( cancel.result){
            _log(`取消订单成功`);
            console.log(cancel);
            return Promise.resolve(true);
        }else{
            _log(`取消订单失败`);
            console.log(cancel);
            return Promise.resolve(false);
        }
    }
    async _createLimitOrder (type,{max_vol, min_vol, markets, switcher, orders, _generateBidOne, _generateAskOne, _log, ok_rest} = this, ){
        // { info: { result: true, order_id: 65474135 }, id: '65474135' }
        const quantity = max_vol;
        let price, ok_limit;
        if(quantity >= min_vol) {
            switcher.ok = false;
            switcher.finex = false;
            if (type === 'bid'){
                price = _generateBidOne(markets.ok.bid[0]);
                ok_limit = await ok_rest.createLimitBuyOrder('BTG/USDT', quantity, price);
            }else{
                price = _generateAskOne(markets.ok.ask[0]);
                ok_limit = await ok_rest.createLimitSellOrder('BTG/USDT', quantity, price);
            }
            if(ok_limit.info.result){

                order.ok_old.id = orders.ok.id;
                orders.ok_old.price = price;
                type === 'bid' ? orders.ok_old.vol = quantity : orders.ok_old.vol = -quantity;
                orders.ok_old.complete = 0;

                orders.ok.id = ok_limit.info.order_id;
                orders.ok.price = price;
                type === 'bid' ? orders.ok.vol = quantity : orders.ok.vol = -quantity;
                orders.ok.complete = 0;

                _log(`OK-${type}-one挂单成功`);
                console.log(ok_limit);
                return Promise.resolve(true);
            }else{
                _log(`OK-${type}-one挂单失败`);
                console.log(ok_limit);
                return Promise.resolve(false);
            }

        }
    }
    async _createMarketOrder (type,{max_vol, min_vol, markets, wallets, switcher, _log, ok_rest, bitfinex_rest} = this){
        if(type === 'order-1'){
            const quantity = Math.min(max_vol, markets.ok.bid[1]/3, Math.abs(markets.finex.ask[1]/3));
            if( quantity > min_vol && wallets.ok.coin[0] >= quantity && wallets.finex.usd>quantity*markets.finex.ask[0]*1.01){
                switcher.ok = false;
                switcher.finex = false;
                _log(`判定通过: quantity${quantity}`);
                const [ok_market,finex_market] = await Promise.all([
                    ok_rest.createMarketSellOrder ('BTG/USDT', quantity),
                    bitfinex_rest.createMarketBuyOrder ('BTG/USD', quantity)]);
                _log(`ok_market finex_market order-1`)
                console.log(ok_market)
                console.log(finex_market)
            }else{
                _log(`判定未通过: quantity${quantity}`);
            }
        }else if(type === 'order-2'){
            const quantity = Math.min(max_vol, Math.abs(markets.ok.ask[1]/3), markets.finex.bid[1]/3);
            if( quantity > min_vol && wallets.finex.coin>=quantity && wallets.ok.usd[0]>quantity*markets.ok.ask[0]*1.01) {
                switcher.ok = false;
                switcher.finex = false;
                _log(`判定通过: quantity${quantity}`);
                const [ok_market,finex_market] = await Promise.all([
                    bitfinex_rest.createMarketSellOrder ('BTG/USD', quantity),
                    ok_rest.createMarketBuyOrder ('BTG/USDT', undefined,{ cost :quantity*markets.ok.ask[0]})]);
                _log(`finex_market ok_market order-2`)
                console.log(finex_market)
                console.log(ok_market)
            }else{
                _log(`判定未通过: quantity${quantity}`);
            }
        }


    }
}
module.exports = Bot;